import csv
import re
import sqlite3

import loguru
# from log_config import logger
import mysql.connector
import gzip
import shutil
import sys
from bs4 import BeautifulSoup
import requests
from lxml import etree
import os
import re

cursor = []
connection = []
proxies = {"http": "http://127.0.0.1:20809", "https": "http://127.0.0.1:20809"}


def connect():
    global cursor, connection
    try:
        connection = mysql.connector.connect(
            host='localhost',
            port=9306,
            database='test',
            buffered=True  # 启用缓冲
        )
        cursor = connection.cursor()
        # 动态设置 max_allowed_packet
        # cursor.execute("SET GLOBAL max_allowed_packet = 33554432")  # 设置为 32M 或其他值
        connection.commit()
    except Exception as e:
        loguru.logger.error(f"error in connect: {e}")
        exit()


def table_name_generator(version):
    table_name = "openeuler-" + version.lower()
    table_name = re.sub(r'[^a-zA-Z0-9]', '_', table_name)
    return table_name


def save_data(version):
    if not cursor:
        connect()
    localdir = "files" + os.sep + version + os.sep
    print('localdir = ', localdir)
    table_name = table_name_generator(version)
    if not os.path.exists(localdir):
        os.makedirs(localdir)
        link_dirs = ['/OS/x86_64/repodata/', '/EPOL/main/x86_64/repodata/', '/everything/x86_64/repodata/']
        for link in link_dirs:
            dirname = "https://repo.openeuler.org/openEuler-" + version + link
            print('dirname=', dirname)
            # response = requests.get(dirname, proxies=proxies)
            try:
                response = requests.get(dirname)
                if response.status_code == 200:
                    soup = BeautifulSoup(response.content, 'html.parser')
                    filenames = [link.get('href') for link in soup.find_all('a')]
                    for filename in filenames:
                        if filename.endswith("-filelists.xml.gz") or filename.endswith("-primary.xml.gz"):
                            response = requests.get(dirname + filename)
                            with open(localdir + filename, 'wb') as file:
                                file.write(response.content)
                            with gzip.open(localdir + filename, 'rb') as f_in:
                                with open(localdir + filename[:-3], 'wb') as f_out:
                                    shutil.copyfileobj(f_in, f_out)
                else:
                    sys.stderr.write("error version\n")
                    delete_table(table_name)
                    return
            except Exception as e:
                loguru.logger.error(f"Failed to get file from {dirname}, Caused by {e}")

    # sql = "INSERT INTO " + table_name + " (rpm_name, files, provides) VALUES (%s, %s, %s)"
    sql = "INSERT INTO " + table_name + " (rpm_name, files, provides, resources) VALUES (%s, %s, %s, %s)"
    cursor.execute('DROP TABLE IF EXISTS ' + table_name)
    # 为了方便查询，rpm_name也设为 text类
    # create_table_sql = f"CREATE TABLE {table_name} (rpm_name string,files text,provides text) charset_table='U+0021,U+0022, U+0024..U+007E' min_infix_len = '5'"
    # create_table_sql = f"CREATE TABLE {table_name} (rpm_name text,files text,provides text) charset_table='U+0021,U+0022, U+0024..U+007E' min_infix_len = '5'"
    create_table_sql = f"CREATE TABLE {table_name} (rpm_name text, files text, provides text, resources text) charset_table='U+0021,U+0022, U+0024..U+007E' min_infix_len = '5'"
    cursor.execute(create_table_sql)
    connection.commit()
    dict = {}

    filelist_namespce = {
        'xmlns': 'http://linux.duke.edu/metadata/filelists'
    }
    primary_namespce = {
        'xmlns': 'http://linux.duke.edu/metadata/common',
        'rpm': 'http://linux.duke.edu/metadata/rpm'
    }

    # for filename in os.listdir(localdir):
    #     if filename.endswith('filelists.xml'):
    #         xml = etree.parse(localdir + filename)
    #         for elem in xml.findall("xmlns:package", namespaces=filelist_namespce):
    #             rpmName = elem.get('name')
    #             files = elem.findall('xmlns:file', namespaces=filelist_namespce)
    #             # filenames = [filename.text.split('/')[-1].lower() for filename in files if
    #             filenames = [filename.text.lower() for filename in files if
    #                          not filename.get('type') == 'dir']
    #             dict.setdefault(rpmName, ['#', '#'])[0] += '#'.join(filenames) + '#'
    #     elif filename.endswith('primary.xml'):
    #         xml = etree.parse(localdir + filename)
    #         for elem in xml.findall("xmlns:package", namespaces=primary_namespce):
    #             rpmName = elem.find('xmlns:name', namespaces=primary_namespce).text
    #             format = elem.find('xmlns:format', namespaces=primary_namespce)
    #             provides = format.find('rpm:provides', namespaces=primary_namespce)
    #             if provides is not None:
    #                 files = provides.findall('rpm:entry', namespaces=primary_namespce)
    #                 filenames = [filename.get('name') for filename in files]
    #                 dict.setdefault(rpmName, ['#', '#'])[1] += '#'.join(filenames) + '#'
    extension_list = ['.h', '.so', '.pc', '.cmake']
    for filename in os.listdir(localdir):
        if filename.endswith('filelists.xml'):
            xml = etree.parse(localdir + filename)
            for elem in xml.findall("xmlns:package", namespaces=filelist_namespce):
                rpmName = elem.get('name')
                files = elem.findall('xmlns:file', namespaces=filelist_namespce)
                # filenames = [filename.text.split('/')[-1].lower() for filename in files if
                filenames = [filename.text.lower() for filename in files if
                             not filename.get('type') == 'dir']
                dict.setdefault(rpmName, ['#', '#', ''])[0] += '#'.join(filenames) + '#'

                resources = []
                for filename in filenames:
                    # basename = os.path.basename(filename)
                    # basename = re.sub(r'\.\d+(\.\d+)*$', '', basename)  无法处理libkf5notifyconfig.so.5.100.0-5.100.0-1.oe2203sp4.x86_64.debug
                    # 去除从第一个版本号开始的所有内容
                    # filename = re.sub(r'\.\d+.*$', '', filename)
                    # 构建正则表达式，只截断extension_list中存在的扩展名之后的数字
                    pattern = r'({})\.\d+.*$'.format('|'.join([re.escape(ext) for ext in extension_list]))
                    filename = re.sub(pattern, r'\1', filename)
                    basename = os.path.basename(filename)

                    _, extension = os.path.splitext(basename)
                    # if filename.startswith('/usr/lib/pkgconfig') or filename.startswith('/usr/lib64/pkgconfig'):
                    #     resources.append(f'pkgconfig:{basename}')
                    # elif filename.startswith('/usr/lib/cmake') or filename.startswith('/usr/lib64/cmake'):
                    #     resources.append(f'cmake:{basename}')
                    # 为了只过滤标准路径下的文件，限制'/'的数目不高于4，即最多保留/usr/lib/xxx/xxx.so
                    # if filename.count('/') <= 4:
                    # if filename.count('/') <= 3 or ('pkgconfig' in filename and filename.count('/') <= 4):
                    if filename.startswith('/usr/lib/'):
                        resources.append(f'lib:{filename[len("/usr/lib/"):]}')
                    elif filename.startswith('/usr/lib64/'):
                        resources.append(f'lib:{filename[len("/usr/lib64/"):]}')
                    elif filename.startswith('/usr/include/'):
                        resources.append(f'include:{filename[len("/usr/include/"):]}')
                    elif filename.startswith('/usr/bin/'):
                        resources.append(f'bin:{filename[len("/usr/bin/"):]}')
                    elif filename.startswith('/usr/share/pkgconfig'):
                        resources.append(f'lib:{filename[len("/usr/share/"):]}')
                    else:
                        # if extension in extension_list:
                        #     resources.append(f'other:{basename}')
                        # 处理特殊情况
                        if filename.startswith('/usr/include/qt5'):
                            resources.append(f'other:private/{basename}')
                        if filename.startswith('/usr/share/bash-completion/completions/'):
                            resources.append(f'other:{filename[len("/usr/share/bash-completion/completions/"):]}')
                        pass
                    # else:
                    #     if extension in extension_list:
                    #         resources.append(f'other:{basename}')

                resources = list(set(resources))

                dict.setdefault(rpmName, ['#', '#', ''])[2] += ' '.join(resources) + ' '


        elif filename.endswith('primary.xml'):
            xml = etree.parse(localdir + filename)
            for elem in xml.findall("xmlns:package", namespaces=primary_namespce):
                rpmName = elem.find('xmlns:name', namespaces=primary_namespce).text
                format = elem.find('xmlns:format', namespaces=primary_namespce)
                provides = format.find('rpm:provides', namespaces=primary_namespce)
                if provides is not None:
                    files = provides.findall('rpm:entry', namespaces=primary_namespce)
                    filenames = [filename.get('name') for filename in files]
                    dict.setdefault(rpmName, ['#', '#', ''])[1] += '#'.join(filenames) + '#'

                    resources = []
                    for filename in filenames:
                        resources.append(f'provides:{filename}')
                    resources = list(set(resources))
                    dict.setdefault(rpmName, ['#', '#', ''])[2] += ' '.join(resources) + ' '

    for key, value in dict.items():
        # 截断超长的字段:
        MAX_LEN = 5000000
        if len(value[0]) > MAX_LEN:
            value[0] = value[0][:MAX_LEN]
        doc = (key, value[0], value[1], value[2])
        cursor.execute(sql, doc)
        connection.commit()

    connection.commit()


# def search(lib, version='22.03-LTS-SP3'):
#     if not cursor:
#         connect()
#     index_name = "openeuler-" + version.lower()
#     index_name = re.sub(r'[^a-zA-Z0-9]', '_', index_name)
#     sql = f"SELECT rpm_name FROM {index_name} WHERE MATCH('\"{lib}\"|\"{lib}.so\"|\"{lib}.a\"|\"lib{lib}\"|\"lib{lib}.so\"|\"lib{lib}.a\"')"
#     # sql = f"SELECT * FROM {index_name} WHERE rpm_name='dietlibc-devel'"
#     cursor.execute(sql)
#     rpms = [rpm[0] for rpm in cursor]
#     return rpms


# save_data('22.03-LTS-SP3')
# print(search('pthread'))
def search_rpm_from_virtual(virtual_name, version):
    if not cursor:
        connect()
    tables = list_tables()
    table_name = table_name_generator(version)
    if table_name not in tables:
        loguru.logger.error(f"Table named<{table_name}> was not Found!")
        return
    # 先用实名查找
    sql = f"SELECT rpm_name FROM {table_name} WHERE MATCH('@rpm_name \"{virtual_name}\"')"

    cursor.execute(sql)
    # 获取结果集
    rows = cursor.fetchall()
    real_rpms = []
    for row in rows:
        rpm_name = row[0]
        real_rpms.append(rpm_name)

    # 确实是虚名
    if len(real_rpms) == 0:
        sql = f"SELECT rpm_name FROM {table_name} WHERE MATCH('@provides \"#{virtual_name}#\"')"
        cursor.execute(sql)
        # 获取结果集
        rows = cursor.fetchall()
        for row in rows:
            rpm_name = row[0]
            real_rpms.append(rpm_name)
    return real_rpms


def fuzzy_search_rpm_from_virtual(virtual_name, version):
    if not cursor:
        connect()
    tables = list_tables()
    table_name = table_name_generator(version)
    if table_name not in tables:
        loguru.logger.error(f"Table named<{table_name}> was not Found!")
        return
    # 先用实名查找
    sql = f"SELECT rpm_name FROM {table_name} WHERE MATCH('@rpm_name \"{virtual_name}\"')"

    cursor.execute(sql)
    # 获取结果集
    rows = cursor.fetchall()
    real_rpms = []
    for row in rows:
        rpm_name = row[0]
        real_rpms.append(rpm_name)

    # 确实是虚名
    if len(real_rpms) == 0:
        sql = f"SELECT rpm_name FROM {table_name} WHERE MATCH('@provides \"*{virtual_name}*\"')"
        # sql = f"SELECT rpm_name FROM {table_name} WHERE provides REGEXP '.*{virtual_name}.*'"

        cursor.execute(sql)
        # 获取结果集
        rows = cursor.fetchall()
        for row in rows:
            rpm_name = row[0]
            real_rpms.append(rpm_name)
    return real_rpms


def search(lib, lib_type, version):
    connect()
    tables = list_tables()
    table_name = table_name_generator(version)
    if table_name not in tables:
        loguru.logger.error(f"Table named<{table_name}> was not Found!")
        return
    '''
        filelists
        lib:xxx
        /lib
        /usr/lib64
        lib:libGeoIP.so
        include:
        bin:geoiplookup
        <file>/usr/bin/geoiplookup</file>
        bin:geoiplookup
        <file>/usr/bin/geoiplookup6</file>
        <file>/usr/lib64/libGeoIP.so.1</file>
        lib:libGeoIP.so
        <file>/usr/lib64/libGeoIP.so.1.6.12</file>
        <file>/usr/lib64/pkgconfig/OpenIPMI.pc</file>
        <file>/usr/share/pkgconfig/xwaylandproto.pc</file>
        match /pkgconfig/*.pc$
                =>
        add col pkgconfig:OpenIPMI.pc
    '''
    # 原字符找一遍
    if lib_type == ".so":
        # prefix = '*/lib*/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}\"|\"{prefix}{lib}.so*\"|\"{prefix}{lib}.a*\"|\"{prefix}lib{lib}\"|\"{prefix}lib{lib}.so*\"|\"{prefix}lib{lib}.a*\"|\"{prefix}lib{lib}api.a*\"|\"{prefix}lib{lib}api.so*\"|\"{prefix}{lib}api.a*\"|\"{prefix}{lib}api.so*\"')  LIMIT 300"
        prefix = 'lib:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}\"|\"{prefix}{lib}.so\"|\"{prefix}{lib}.a\"|\"{prefix}lib{lib}\"|\"{prefix}lib{lib}.so\"|\"{prefix}lib{lib}.a\"|\"{prefix}lib{lib}api.a\"|\"{prefix}lib{lib}api.so\"|\"{prefix}{lib}api.a\"|\"{prefix}{lib}api.so\"')  LIMIT 300"
    elif lib_type == ".h":
        # prefix = '/usr/include/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}.h\"') LIMIT 300"
        prefix = 'include:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}.h\"') LIMIT 300"
    elif lib_type == ".pc":
        # prefix = '/usr/lib*/pkgconfig/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}.pc\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = 'lib:pkgconfig/'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}.pc\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == "program":
        # prefix = '/usr/bin/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = 'bin:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == '.cmake':
        # prefix = f'/usr/lib*/cmake/{lib}/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}Connfig.cmake\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = f'lib:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}Connfig.cmake\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == "perl":
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"perl({lib})\"') LIMIT 300"
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"perl({lib})\"') LIMIT 300"
    else:
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{lib}\"') LIMIT 300"
    # sql = f"SELECT * FROM {index_name} WHERE rpm_name='dietlibc-devel'"
    # 执行查询
    rpms_with_provides = []

    cursor.execute(sql)
    # 获取结果集
    rows = cursor.fetchall()
    is_empty = False

    if len(rows) == 0:
        is_empty = True
    else:
        # 提取所需数据
        for row in rows:
            rpm_name = row[0]
            rpms_with_provides.append(rpm_name)
            provides = row[1].split('#') if row[1] else []
            for provide in provides:
                provide = provide.replace(' ', "")
                # if provide != '':
                #     rpms_with_provides.append(provide)

    # 如果都没找到，就去other里面找找非标准的
    if is_empty:
        prefix = f'other:'
        suffix = lib_type
        if lib_type == 'program' or lib_type == 'perl':
            suffix = ''

        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}{suffix}\"') LIMIT 300"
        cursor.execute(sql)
        # 获取结果集
        rows = cursor.fetchall()
        # 提取所需数据
        for row in rows:
            rpm_name = row[0]
            rpms_with_provides.append(rpm_name)
            provides = row[1].split('#') if row[1] else []
            for provide in provides:
                provide = provide.replace(' ', "")
                # if provide != '':
                #     rpms_with_provides.append(provide)

    # 小写找一遍
    lib = lib.lower()
    if lib_type == ".so":
        # prefix = '*/lib*/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}\"|\"{prefix}{lib}.so*\"|\"{prefix}{lib}.a*\"|\"{prefix}lib{lib}\"|\"{prefix}lib{lib}.so*\"|\"{prefix}lib{lib}.a*\"|\"{prefix}lib{lib}api.a*\"|\"{prefix}lib{lib}api.so*\"|\"{prefix}{lib}api.a*\"|\"{prefix}{lib}api.so*\"')  LIMIT 300"
        prefix = 'lib:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}\"|\"{prefix}{lib}.so\"|\"{prefix}{lib}.a\"|\"{prefix}lib{lib}\"|\"{prefix}lib{lib}.so\"|\"{prefix}lib{lib}.a\"|\"{prefix}lib{lib}api.a\"|\"{prefix}lib{lib}api.so\"|\"{prefix}{lib}api.a\"|\"{prefix}{lib}api.so\"')  LIMIT 300"
    elif lib_type == ".h":
        # prefix = '/usr/include/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}.h\"') LIMIT 300"
        prefix = 'include:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}.h\"') LIMIT 300"
    elif lib_type == ".pc":
        # prefix = '/usr/lib*/pkgconfig/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}.pc\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = 'lib:pkgconfig/'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}.pc\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == "program":
        # prefix = '/usr/bin/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = 'bin:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == '.cmake':
        # prefix = f'/usr/lib*/cmake/{lib}/'
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{prefix}{lib}Connfig.cmake\"|\"pkgconfig({lib})\"') LIMIT 300"
        prefix = f'lib:'
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}connfig.cmake\"|\"pkgconfig({lib})\"') LIMIT 300"

    elif lib_type == "perl":
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"perl({lib})\"') LIMIT 300"
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"perl({lib})\"') LIMIT 300"
    else:
        # sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{lib}\"|\"pkgconfig({lib})\"') LIMIT 300"
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('\"{lib}\"') LIMIT 300"
        '''
        TODO:
        size lines 1w lines
        files
        file1
        file2
        file10000
        file10001


wfg /c/linux/include/uapi% ls
asm-generic  drm  Kbuild  linux  misc  mtd  rdma  regulator  scsi  sound  video  xen


        input: /usr/include/xxx
        out: include/xxx
        input: path
        output: path { /usr/sbin/curl => bin/curl } {/usr/lib64/xxx.so => lib/xxx.so}
        => db text index


        find_program.curl
        => bin/curl


        find_library.curl
        => lib/curl




        /bin/curl
        /usr/bin/curl
        /usr/sbin/curl
        /usr/X11R6/bin/curl

        PATH

        full text search db

        command field
        '''

    # sql = f"SELECT * FROM {index_name} WHERE rpm_name='dietlibc-devel'"
    cursor.execute(sql)
    # 获取结果集
    rows = cursor.fetchall()
    is_empty = False

    if len(rows) == 0:
        is_empty = True
    else:
        # 提取所需数据
        for row in rows:
            rpm_name = row[0]
            is_empty = len(rpm_name) == 0
            rpms_with_provides.append(rpm_name)
            provides = row[1].split('#') if row[1] else []
            for provide in provides:
                provide = provide.replace(' ', "")
                # if provide != '':
                #     rpms_with_provides.append(provide)

    # 如果都没找到，就去other里面找找非标准的
    if is_empty:
        prefix = f'other:'
        suffix = lib_type
        if lib_type == 'program' or lib_type == 'perl':
            suffix = ''
        sql = f"SELECT rpm_name, provides FROM {table_name} WHERE MATCH('@resources \"{prefix}{lib}{suffix}\"') LIMIT 300"
        cursor.execute(sql)
        # 获取结果集
        rows = cursor.fetchall()
        # 提取所需数据
        for row in rows:
            rpm_name = row[0]
            rpms_with_provides.append(rpm_name)
            provides = row[1].split('#') if row[1] else []
            for provide in provides:
                provide = provide.replace(' ', "")
                # if provide != '':
                #     rpms_with_provides.append(provide)

    rpms = set(rpms_with_provides)
    return rpms


def export_data_from_version(version):
    MAX_MATCHES = 30000
    connect()
    # cursor = connection.cursor()
    table_name = table_name_generator(version)
    # 查询数据
    query = f"SELECT * FROM {table_name} LIMIT {MAX_MATCHES} OPTION max_matches={MAX_MATCHES}"
    print(query)
    cursor.execute(query)
    # 获取查询结果的列名
    columns = [desc[0] for desc in cursor.description]
    # 读取查询结果
    rows = cursor.fetchall()
    print(len(rows))
    # 将数据写入 CSV 文件
    csv_file = f"{table_name}.csv"
    with open(csv_file, 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(columns)  # 写入列名
        writer.writerows(rows)  # 写入数据行

    print(f"数据已导出到 {csv_file}")


def export_data_from_name(table_name):
    connect()
    MAX_MATCHES = 10000
    # 查询数据
    query = f"SELECT * FROM {table_name} LIMIT {MAX_MATCHES} OPTION max_matches={MAX_MATCHES}"
    cursor.execute(query)

    # 获取查询结果的列名
    columns = [desc[0] for desc in cursor.description]

    # 读取查询结果
    rows = cursor.fetchall()

    # 将数据写入 CSV 文件
    csv_file = f"{table_name}.csv"
    with open(csv_file, 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(columns)  # 写入列名
        writer.writerows(rows)  # 写入数据行

    print(f"数据已导出到 {csv_file}")


def list_tables():
    # 假设你已经有了连接 MySQL 数据库的函数 connect()
    connect()
    cursor.execute("SHOW TABLES")
    tables = [db[0] for db in cursor.fetchall()]
    return tables


def create_tables(version):
    table_name = table_name_generator(version)
    save_data(version)
    loguru.logger.info(f"Create a table named <{table_name}>")


# 删除表格的函数
def delete_table(table_name):
    # 连接到数据库
    connect()
    try:
        # 删除表格
        cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
        connection.commit()
        loguru.logger.info(f"Deleted a table named <{table_name}>")
    except Exception as e:
        loguru.logger.error(f"An error occurred while deleting table: {e}")
    finally:
        cursor.close()


if __name__ == '__main__':
    os_version = "22.03-LTS-SP4"
    table_name = table_name_generator(os_version)

    # print(search('private/qguiapplication_p','.h','22.03-LTS-SP4'))
    # print(search_rpm_from_virtual("qt5-qtbase-private-devel",'22.03-LTS-SP4'))
    # print(fuzzy_search_rpm_from_virtual('aether-transport-wa', '22.03-LTS-SP4'))
    # tables = list_tables()
    # print("数据库中所有TABLE的名称:")
    # for name in tables:
    #     print(name)
    # delete_table(table_name)
    # tables = list_tables()
    # print("数据库中所有TABLE的名称:")
    # for name in tables:
    #     print(name)
    # create_tables(os_version)
    # tables = list_tables()
    # print("数据库中所有TABLE的名称:")
    # for name in tables:
    #     print(name)


    # save_data(os_version)

    print(search('perl-Math-BigInt','','22.03-LTS-SP4'))
    # print(search('python3.9/site-packages/pypamtest', '.so', '22.03-LTS-SP4'))
    # print(search_rpm_from_virtual("ghc-Cabal-devel",'22.03-LTS-SP4'))
    # print(fuzzy_search_rpm_from_virtual('aether-transport-wagon', '22.03-LTS-SP4'))
    # print(fuzzy_search_rpm_from_virtual('aether-transport-w', '22.03-LTS-SP4'))

    # print(search('protobuf-c', ".so", '22.03-LTS-SP4'))

    # create_tables(os_version)

    # save_data(table_name)
    # create_tables(os_version)

    # print(search('asm-commons', "", '22.03-LTS-SP4'))
    # test_list = []
    # test_list = fuzzy_search_rpm_from_virtual('maven-project', '22.03-LTS-SP4')
    # test_list = fuzzy_search_rpm_from_virtual('aether-transport', '22.03-LTS-SP4')
    # print(test_list)
    # print(search('mvn(org.eclipse.aether:aether-transport-wagon)', "", '22.03-LTS-SP4'))
    '''
    需求：
    1. 分析未找到的rpm包
    2. 
    '''

    # print(search_rpm_from_virtual('mvel',  '22.03-LTS-SP4'))

    # 查询测试
    # connect()
    # table_name = table_name_generator('22.03-LTS-SP4')
    # lib = 'Qt5Core'
    # query = f"SELECT rpm_name FROM {table_name} WHERE MATCH('@files libpthread*')"
    # cursor.execute(query)
    # rows = cursor.fetchall()
    # rpms = [row[0] for row in rows]
    # print(rpms)

    # 列出所有表
    # tables = list_tables()
    # print("数据库中所有TABLE的名称:")
    # for name in tables:
    #     print(name)

    # 搜索特例
    # connect()
    # sql = search("Qt5Core",".so",'22.03-LTS-SP4')

    # cursor.execute(sql)
    # rpms = [rpm[0] for rpm in cursor]
    # print(rpms)

    # 导出
    # export_data_from_version(os_version)
